package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"guo-group/cache"
	"guo-group/models"
	"guo-group/pkg"
	"time"
)

type GroupController struct {
	beego.Controller
}
type Red struct {
	Code int
	Data interface{}
	Msg  string
}

// log注册
func (c *GroupController) Log() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Red{
			Code: 500,
			Data: nil,
			Msg:  "用户和密码不能为空",
		}
		c.ServeJSON()
	}
	deng := models.User{
		Username: username,
		Password: pkg.Mad5(password),
	}
	err := models.Db.Create(&deng).Error
	if err != nil {
		c.Data["json"] = Red{
			Code: 500,
			Data: nil,
			Msg:  "注册失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Red{
			Code: 200,
			Data: deng,
			Msg:  "注册成功",
		}
		c.ServeJSON()
	}
}

// 登录判断
func (c *GroupController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Red{
			Code: 500,
			Data: nil,
			Msg:  "账号密码不能为空",
		}
		c.ServeJSON()
		return
	}
	data := "data_111"
	i, _ := cache.Rdb.Get(cache.Ctx, data).Int()
	if i >= 3 {
		c.Data["json"] = Red{
			Code: 500,
			Data: nil,
			Msg:  "错误三次禁止登录",
		}
		c.ServeJSON()
	}
	var m models.User
	err := models.Db.Where("username=?", username).First(&m).Error
	if err != nil {
		c.Data["json"] = Red{
			Code: 500,
			Data: nil,
			Msg:  "账号不存在",
		}
		c.ServeJSON()
		return
	}
	if m.Password != pkg.Mad5(password) {
		cache.Rdb.Incr(cache.Ctx, data)
		if i == 2 {
			cache.Rdb.Set(cache.Ctx, data, 3, time.Hour*3)
			c.Data["json"] = Red{
				Code: 500,
				Data: nil,
				Msg:  "错误三次,封禁3小时",
			}
			c.ServeJSON()
			return
		}
		c.Data["json"] = Red{
			Code: 500,
			Data: nil,
			Msg:  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Red{
		Code: 200,
		Data: nil,
		Msg:  "登陆成功",
	}
	c.ServeJSON()
}

// 添加
func (c *GroupController) Add() {

}

// 查询外加缓存
func (c *GroupController) List() {

}

// 删除
func (c *GroupController) Del() {

}
